package opt_socket

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"sync"
)

func http_web_8000() {

	webHandler := func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("==== request is ", r)
		fmt.Println("==== response is ", w)
	}
	http.HandleFunc("/http_web", webHandler)

	// 监听端口
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("err is ", err)
	}
}

func http_client() {
	resp, err := http.Get("http://127.0.0.1:8080/http_web")
	if err != nil {
		fmt.Println("===== err=====", err)
	}

	code := resp.StatusCode
	fmt.Println("code is ", code)
}

func http_client_01() {
	resp, err := http.Get("https://43.134.191.4/")
	if err != nil {
		fmt.Println("get failed，err:", err)
		return
	}
	defer resp.Body.Close()
	all, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get failed，err:", err)
	}
	fmt.Println(string(all))

}

func http_client_02() {
	m := make(map[string]string)
	m["str"] = "value"
	marshal, err := json.Marshal(m)
	if err != nil {
		fmt.Println("err marshal ", err)
	}
	request, err := http.NewRequest("GET",
		"https://www.baidu.com", bytes.NewReader(marshal))
	if err != nil {
		fmt.Println("err is ", err)
	}

	do, err := http.DefaultClient.Do(request)

	if err != nil {
		fmt.Println("read body err:", err)
	}
	all, err := io.ReadAll(do.Body)
	if err != nil {
		fmt.Println("get body err ,", err)
	}

	fmt.Println("response body is", string(all))
}

var wg sync.WaitGroup

// 并发扫描服务器开通端口
func Scan_port() {

	for i := 1; i <= 65535; i++ {
		wg.Add(1)
		go func(port int) {
			defer wg.Done()
			sprintf := fmt.Sprintf("127.0.0.1:%d", port)
			dial, err := net.Dial("tcp", sprintf)
			if err != nil {
				return
			}
			dial.Close()
			fmt.Printf("%d open\n", port)
		}(i)
	}
	wg.Wait()
}
